/* Start Gauge Code */
var casing = new Image();

var sVal = 0; 
var fVal = 0; 
var cVal = 0;
var sVal = 0;
var id = 0;

function draw() {
  	if(sVal == fVal){
		$clear(id);
		fVal = fVal+1;
		return ;
  	}else if (sVal < fVal && cVal >= fVal) {
		$clear(id);
  	}else if (sVal > fVal && cVal <= fVal) {
		$clear(id);
 	}
  
  	var inc  = 1;
  	var perc = (Math.abs(fVal-cVal)/Math.abs(fVal-sVal));
  
  	if (perc < .2) { inc *= perc*7; }
  
  	if (inc < .5) { inc = .5; }
  
  	var dVal = -.5*Math.PI + (cVal/100)*2*Math.PI;
  	cVal += (sVal < fVal) ? inc : -inc;
	
  	var ctx = document.getElementById('myCanvas').getContext('2d');
  
  	// Create the canvas gauge.
  	ctx.globalCompositeOperation = 'destination-over';
  	ctx.clearRect(0,0,200,200); // clear canvas

  	ctx.fillStyle = 'rgba(125,125,125,1.0)';
  	ctx.strokeStyle = 'rgba(255, 0, 0 ,1.0)';
  	ctx.save();
  	ctx.translate(100,105);
  
  	// TESTING : show value
	$('peek').set('html',"Last value: "+sVal+" Current value: "+fVal);
  	// TESTING : show value
  
  	// rotate the needle
  	ctx.rotate(dVal);
  
  	// draw the needle; could be an image.
  	ctx.lineWidth = 3;
  	ctx.lineCap = "round";
  	ctx.moveTo(1.9,0);
  	ctx.lineTo(50,0);
  	ctx.stroke();
  	ctx.restore();
  
  	ctx.beginPath();
  	// Add the cap on the needle
 	ctx.drawImage(casing,0,0,casing.width,casing.height);
}

/* Start Controller Code */
window.addEvent('domready', function() {
	
	//testing a loop javascript requesting live data via Ajax...
	casing.src = 'images/gauge_button.png';
	sVal=0; 
	fVal=1; 
	cVal = sVal;
	draw(id);
	
	function getUpdate(){	
		var request = new Request.JSON({
				url: 'data/gauge.json',
				onComplete: function(jsonObj) {
					glbJSON = jsonObj
					var mydata = jsonObj.mygauge;
					
					// Your live values/data go here. 
					sVal  = Number(mydata[0].startval); // SET START VALUE
					fVal  = Number(mydata[0].endval);   // SET END VALUE

					cVal = sVal;
					$clear(id);
					
  					casing.src = 'images/gauge_button.png';
  					id = draw.periodical(100); 
					
					//var mydata = jsonObj.Columbus;
					//$('mydiv').set('html','<div style="background-color: #e0e0e0; border-bottom: 1px solid #000000; padding-left:2px;">' + mydata[0].title + '</div><div style="background-color: #ffffff; border-bottom: 1px solid #000000; padding-left:2px;">' + mydata[1].title + '</div>');
				}
			}).send();
		}
	var intUpdate = getUpdate.periodical(10000);
});


// PYTHON~ 
//>>> 
//>>> dict = {'columbus':[{'title':'something happened','desc':'desc of that incident'}]}
//>>> e = simplejson.JSONEncoder()
//>>> e.encode(dict)
//'{"columbus": [{"desc": "desc of that incident", "title": "something happened"}]}'
//>>> 